﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using CryptoFiles.Logic;

namespace CryptoFiles.Web
{
    /// <summary>
    /// Summary description for CryptoFile
    /// </summary>
    public class CryptoFile : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            if (context.User.Identity.IsAuthenticated == false) return;


            string fileName = context.Request["file"];
            string user = context.User.Identity.Name;

            CryptoUser cryptoUser = new CryptoUser(user);

            try
            {
                byte[] fileContent = cryptoUser.GetFile(fileName);

                if (fileContent != null)
                {
                    context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
                    context.Response.BinaryWrite(fileContent);
                }
            }
            catch (CryptographicException)
            {
                context.Response.Redirect("MyFiles.aspx?errorfile=" + context.Server.UrlEncode(fileName));
            }
            catch (IOException)
            {
                context.Response.Redirect("MyFiles.aspx?errorfile=" + context.Server.UrlEncode(fileName));
            }
            
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}